﻿using System;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace CzfSDK
{
	public class CzfTcpListener : CzfNetListener
	{
		public int iBacklog;

		private bool started = false;
		public CzfTcpListener (int iPort, int iBacklog = 1024)
		{
			this.port = iPort;	
			this.iBacklog = iBacklog;
		}

		public override void Start(){
			var thread = new Thread (MyStart);
			thread.Start ();
//			sock.BeginAccept(AcceptCallBack, sock);
		}

		void MyStart()
		{
			if (started) {
				throw new Exception ("重复启动监听！");
			} else {
				started = true;
			}

			var ipe = new IPEndPoint (IPAddress.Any, port);
			var sock = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
			sock.Bind (ipe);
			sock.Listen (iBacklog);

			while (true) {
				var client = sock.Accept();
				try{
					if(CzfNetManager.current.debug)
						CzfLog.Info("recive client");
					//结束异步Accept并获已连接的Socket
					ThreadTool.LogThread();
					if(OnAccept != null)
						OnAccept (this, new CzfTcpClient(client));
				}catch(Exception e) {
					CzfLog.Error("CzfTcpListener", e);
				}
			}

		}

		// 异步方案
		void AcceptCallBack(IAsyncResult ar)
		{
			var socket = ar.AsyncState as Socket;
			var client = socket.EndAccept(ar);
			try{
				//结束异步Accept并获已连接的Socket
				ThreadTool.LogThread();
				if(OnAccept != null)
					OnAccept (this, new CzfTcpClient(client));
			}catch(Exception e) {
				CzfLog.Error("CzfTcpListener", e);
			}

			//继续异步Accept，保持Accept一直开启！
			socket.BeginAccept(AcceptCallBack, socket); 
		}
	}
}

